import {BOOKS_ISADMIN,BOOKS,ADD,REMOVE,UPDATE,SELECT_VERSION} from '../actions/books.action';

const initState = {
	isAdmin:0,
	books:[]
}

function Books(state=initState,action) {

	switch (action.type){
		case SELECT_VERSION:
		// selected
			let data = action.data;
			for(let i = 0; i < state.books.length; i++){
				let book = state.books[i];
				if (data.parentId && data.parentId == book.parentId) {
					book.books.forEach(bk => bk.selected = bk.version === data.version);
					break;
				}
			}
			return {...state,...{books:[...state.books]}};
		case BOOKS_ISADMIN:
			state.isAdmin = action.admin;
			return {...state};
		case BOOKS:
			return {...state,...{books:action.books}};
		case ADD:
			action.data.newData=1;
			return {...state,...{books:[...state.books,...[action.data]]}};
		case REMOVE:
			let adata = action.data;
			let books = [...state.books];
			for(let i=0;i<state.books.length;i++){
				let book = state.books[i];
				if (book.parentId && book.parentId === adata.parentId && book.books) {
					book.books = book.books.filter(bk => bk.id !== adata.id);
					if (!book.books.length) books.splice(i,1);
				}

				if (book.id === adata.id) books.splice(i,1);
			}
			return {...state,...{books}};
		case UPDATE:
			const resBook = action.data;
			state.books.forEach(bk=>{
				if (resBook.parentId) {
					if (bk.parentId===resBook.parentId) {
						for(let item in resBook){
							bk[item]=resBook[item];
						}
					}
				}
				if (resBook.id) {
					if (bk.id===resBook.id) {
						for(let item in resBook){
							bk[item]=resBook[item];
						}
					}
				}
			});
			return {...state,...{books:state.books}};
		default :
			return {...state};
	}
}

export default Books;